package com.koron.css2.projectCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.BankBean;
import com.koron.css2.baseConfig.bean.ProjectPayeeBean;
import com.koron.css2.baseConfig.mapper.BankMapper;
import com.koron.css2.baseConfig.mapper.BusinessAbodeMapper;
import com.koron.css2.baseConfig.mapper.BusinessAreaMapper;
import com.koron.css2.baseConfig.mapper.ProjectPayeeMapper;
import com.koron.css2.baseConfig.vo.SelectVO;
import com.koron.css2.clientCenter.bean.AccountInfoBean;
import com.koron.css2.clientCenter.bean.CtmInfoBean;
import com.koron.css2.clientCenter.mapper.AccountInfoMapper;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.projectCenter.bean.PjConsultBean;
import com.koron.css2.projectCenter.bean.query.PjConsultQueryBean;
import com.koron.css2.projectCenter.mapper.PjConsultMapper;
import com.koron.css2.projectCenter.vo.PjConsultDetailVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.DictionaryMapper;
import com.koron.css2.serviceManage.mapper.DistrictMapper;
import com.koron.css2.serviceManage.mapper.PubAdminAreaMapper;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.serviceManage.vo.DictionaryVO;
import com.koron.css2.systemManage.bean.OrgUserBean;
import com.koron.css2.systemManage.bean.OrgUserQueryBean;
import com.koron.css2.systemManage.mapper.OrgUserMapper;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 用水咨询详情
 * @author 许海宜
 * 2020年3月5日
 */
public class PjConsultQuery implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		try {
			//将入参转换为QueryBean
			PjConsultQueryBean queryBean = JsonUtils.objectToPojo(req.getData(), PjConsultQueryBean.class);
			if(StringUtils.isBlank(queryBean.getId())) {
				return MessageBean.create(Constant.NOT_NULL, "主键不能为空。", null);
			}
			
			//查询工程信息
			PjConsultMapper mapper = factory.getMapper(PjConsultMapper.class);
			PubAdminAreaMapper pmapper = factory.getMapper(PubAdminAreaMapper.class,"_default");
			PjConsultBean pjConsultBean = mapper.selectById(queryBean.getId());
			if (pjConsultBean == null) {
				return MessageBean.create(Constant.NOT_NULL, "用水咨询单据不存在。", null);
			}
			//查询客户信息
			Integer updateCtmFlag = 0;
			CtmInfoMapper ctmMapper = factory.getMapper(CtmInfoMapper.class);
			//查询临时表
			CtmInfoBean ctmInfoBean = ctmMapper.getCtmInfoById(pjConsultBean.getUserCtmTempId(), 2);
			//判断正式表是否存在，不存在则允许修改
			if(ctmInfoBean==null||ctmMapper.getCtmInfoByCtmNo(ctmInfoBean.getCtmNo(), 1) == null) {
				updateCtmFlag = 1;
			}
			if(!StringUtils.isEmpty(ctmInfoBean.getClientAddr())) {
				String area = pmapper.selectFullNameById(ctmInfoBean.getClientAddr());
				ctmInfoBean.setClientAddr(area);
			}
			//查询账户信息
			Integer updateAccountFlag = 0;
			AccountInfoMapper accountMapper = factory.getMapper(AccountInfoMapper.class);
			//查询临时表
			AccountInfoBean accountInfoBean = accountMapper.getAccountInfoById(pjConsultBean.getUserAccountTempId(), 2);
			//判断正式表是否存在，不存在则允许修改
			if(accountInfoBean==null||accountMapper.getAccountInfoByCode(accountInfoBean.getAccountNo(), 1) == null) {
				updateAccountFlag = 1;
				
			}
			if(accountInfoBean == null)
				accountInfoBean = new AccountInfoBean();
			
			//根据业务节点将只读字段进行数据字典转换
			convertStatus(factory, pjConsultBean, ctmInfoBean, accountInfoBean,userInfo);
			Map<String, String> IDT = Tools.mapDicByCode(factory, "IDT");
			Map<String, String> PCW = Tools.mapDicByCode(factory, "PCW");//结算方式
			if(!StringUtils.isBlank(pjConsultBean.getAgentCertType())) {
				pjConsultBean.setAgentCertTypeName(IDT.get(pjConsultBean.getAgentCertType()));
			}
			if(!StringUtils.isBlank(pjConsultBean.getPrepayType())) {
				pjConsultBean.setPrepayTypeName(PCW.get(pjConsultBean.getPrepayType()));
			}
			if(pjConsultBean.getDepositMoney()==null) {
				pjConsultBean.setDepositMoney(0.0);
			}
			//转化岗位人员名称
			OrgUserMapper omapper = factory.getMapper(OrgUserMapper.class);
			if(!StringUtils.isBlank(pjConsultBean.getInstallStaff())) {
				OrgUserQueryBean orgUserQueryBean = new OrgUserQueryBean();
				orgUserQueryBean.setUserAccounts(Arrays.asList(pjConsultBean.getInstallStaff().split(",")));
				List<OrgUserBean> olist = omapper.selectByAccounts(orgUserQueryBean);
				if(olist!=null && olist.size()>0) {
					List<String> installStaffName = new ArrayList<String>();
					for (int i=0;i<olist.size();i++) {
						installStaffName.add(olist.get(i).getUserName());
					}
					pjConsultBean.setInstallStaffName(String.join(",", installStaffName));
				}
			}
			if(!StringUtils.isBlank(pjConsultBean.getSurveyStaff())) {
				OrgUserBean user = omapper.selectByAccount(pjConsultBean.getSurveyStaff());
				pjConsultBean.setSurveyStaffName(user==null?"":user.getUserName());
			}
			if(!StringUtils.isBlank(pjConsultBean.getDesignStaff())) {
				OrgUserBean user = omapper.selectByAccount(pjConsultBean.getDesignStaff());
				pjConsultBean.setDesignStaffName(user==null?"":user.getUserName());
			}
			if(!StringUtils.isBlank(pjConsultBean.getBudgetStaff())) {
				OrgUserBean user = omapper.selectByAccount(pjConsultBean.getBudgetStaff());
				pjConsultBean.setBudgetStaffName(user==null?"":user.getUserName());
			}
			if(!StringUtils.isBlank(pjConsultBean.getBudgetPayStaff())) {
				OrgUserBean user = omapper.selectByAccount(pjConsultBean.getBudgetPayStaff());
				pjConsultBean.setBudgetPayStaffName(user==null?"":user.getUserName());
			}
			
			//输出VO组装selectByAccount
			PjConsultDetailVO detailVO = new PjConsultDetailVO();
			pjConsultBean.setPrepayMoney((pjConsultBean.getBudgetMoney()==null?0.0:pjConsultBean.getBudgetMoney())+(pjConsultBean.getDepositMoney()==null?0.0:pjConsultBean.getDepositMoney()));
			detailVO.setConsult(pjConsultBean);
			detailVO.setCtmInfo(ctmInfoBean);
			detailVO.setAccountInfo(accountInfoBean);
			detailVO.setUpdateCtmFlag(updateCtmFlag);
			detailVO.setUpdateAccountFlag(updateAccountFlag);
			//判断是否审批节点
			detailVO.setApproveFlag(0);
			if(!StringUtils.isBlank(pjConsultBean.getProcessState()) 
					&& ("CANCEL".equals(pjConsultBean.getProcessState())
							|| "END".equals(pjConsultBean.getProcessState())
							|| isApproval(pjConsultBean.getProcessState()))) {
				//pjConsultBean.setProcessState(pjConsultBean.getProcessState().replace("-approval", ""));
				detailVO.setApproveFlag(1);
			}
			//输出分页结果
			MessageBean<PjConsultDetailVO> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功", PjConsultDetailVO.class);
			info.setData(detailVO);
			return info;
		} catch (Exception e) {
			logger.error("用水咨询详情查询失败"+e.getMessage(), e);
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "查询失败", null);
		}
	}
	/**
	 * 判断流程状态
	 */
	public boolean isApproval(String process) {
		if(!"survey".equals(process) && !"design".equals(process) && !"budget".equals(process)
				&& !"register".equals(process)) {
			return true;
		}
		return false;
		
	}
	/**
	 * 字段转换
	 * @param factory
	 * @param pjConsultBean
	 * @param ctmInfoBean
	 * @param accountInfoBean
	 */
	public void convertStatus(SessionFactory factory, PjConsultBean pjConsultBean, 
			CtmInfoBean ctmInfoBean, AccountInfoBean accountInfoBean,UserInfoBean userInfo) {
		DictionaryMapper dictionaryMapper = factory.getMapper(DictionaryMapper.class);
		String codes[] = "CTT,IDT,CDL,PPT,EGD,ACT,BBT,SDW,PIS,UWD,BPW,PJC".split(",");
		List<DictionaryVO> list = dictionaryMapper.findDictionaryByCodes(codes);
		//预算节点
		BankMapper bankeMapper = factory.getMapper(BankMapper.class);
		BusinessAbodeMapper Businessmapper = factory.getMapper(BusinessAbodeMapper.class,"_default");
		for (DictionaryVO d : list) {
			if(ctmInfoBean.getCtmType()!=null && "CTT".equals(d.getCode())&&ctmInfoBean.getCtmType().equals(d.getValue())){
				//客户类型
				ctmInfoBean.setCtmTypeName(d.getName());
			} else if(ctmInfoBean.getCertType()!=null && "IDT".equals(d.getCode())&&ctmInfoBean.getCertType().equals(d.getValue())){
				//证件类型
				ctmInfoBean.setCertTypeName(d.getName());
			} else if(ctmInfoBean.getCreditLevel()!=null && "CDL".equals(d.getCode())&&ctmInfoBean.getCreditLevel().equals(d.getValue())){
				//信用级别
				ctmInfoBean.setCreditLevelName(d.getName());
			} else if(pjConsultBean.getPjType()!=null && "PPT".equals(d.getCode())&&pjConsultBean.getPjType().equals(d.getValue())){
				//工程类型
				pjConsultBean.setPjTypeName(d.getName());
			} else if(pjConsultBean.getUrgentFlag() !=null && "EGD".equals(d.getCode())&&pjConsultBean.getUrgentFlag().equals(d.getValue())){
				//紧急程度
				pjConsultBean.setUrgentFlagName(d.getName());
			} else if(accountInfoBean.getAccountType() != null && "ACT".equals(d.getCode())&&accountInfoBean.getAccountType().equals(d.getValue())){
				//账户类型
				accountInfoBean.setAccountTypeName(d.getName());
			} else if(accountInfoBean.getInvoiceType() != null && "BBT".equals(d.getCode())&&accountInfoBean.getInvoiceType().equals(d.getValue())){
				//发票类型
				accountInfoBean.setInvoiceTypeName(d.getName());
			} else if(accountInfoBean.getDeliverWay() != null && "SDW".equals(d.getCode())&&accountInfoBean.getDeliverWay().equals(d.getValue())){
				//投递方式
				accountInfoBean.setDeliverWayName(d.getName());
			} else if(pjConsultBean.getSourceFlag() !=null && "PIS".equals(d.getCode())&&pjConsultBean.getSourceFlag().equals(d.getValue())){
				//信息来源
				pjConsultBean.setSourceFlagName(d.getName());
			} else if(pjConsultBean.getLimitFlag()!=null && "UWD".equals(d.getCode())&&pjConsultBean.getLimitFlag().equals(d.getValue())){
				//用水期
				pjConsultBean.setLimitFlagName(d.getName());
			} else if(accountInfoBean.getPayWay()  !=null && "BPW".equals(d.getCode())&&accountInfoBean.getPayWay().equals(d.getValue())){
				//缴费方式
				accountInfoBean.setPayWayName(d.getName());
			} 
		}
		if(pjConsultBean.getProjectCharge()  !=null){
			//收款主体
			ProjectPayeeBean bean = new ProjectPayeeBean();
			bean.setId(pjConsultBean.getProjectCharge());
			ProjectPayeeMapper mapper = factory.getMapper(ProjectPayeeMapper.class);
			ProjectPayeeBean rojectPayeeBean = mapper.query(bean);
			pjConsultBean.setProjectCharge(rojectPayeeBean!=null?rojectPayeeBean.getSubjectName():"");
		}
		if(StringUtils.isNotBlank(accountInfoBean.getVatFlag()) && "1".equals(accountInfoBean.getVatFlag())) {
			accountInfoBean.setVatFlagName("是");
		}else {
			accountInfoBean.setVatFlagName("否");
		}
		//开户行
		if(!StringUtils.isBlank(accountInfoBean.getOpenAccountBank())){
			BankMapper bankMapper = factory.getMapper(BankMapper.class);
			BankBean bankBean = bankMapper.findBankById(accountInfoBean.getOpenAccountBank());
			accountInfoBean.setOpenAccountBankName(bankBean.getBankName());
		}
		// 获取购买方开户行名称
		if (!StringUtils.isBlank(accountInfoBean.getInvoiceBank())) {
			BankBean bankName = bankeMapper.findBankById(accountInfoBean.getInvoiceBank());
			accountInfoBean.setInvoiceBankName(bankName==null?"":bankName.getBankName());
		}
		// 获取行政区域
		if (!StringUtils.isEmpty(pjConsultBean.getAdminArea())) {
			DistrictMapper districtMapper = factory.getMapper(DistrictMapper.class);
			pjConsultBean.setAdminAreaName(districtMapper.findDistrictById(pjConsultBean.getAdminArea()).getSname());
		}
		// 获取营业区域
		if (!StringUtils.isEmpty(pjConsultBean.getBusinessArea())) {
			BusinessAreaMapper businessAreaMapper = factory.getMapper(BusinessAreaMapper.class);
			pjConsultBean.setBusinessAreaName(
					businessAreaMapper.findBusinessAreaById(pjConsultBean.getBusinessArea(), userInfo.getCurWaterCode()));
		}
		//营业所
		//获取下拉框
		List<SelectVO> blist = Businessmapper.businessAbodeSelect(userInfo.getCurWaterCode());
		for (SelectVO selectVO : blist) {
			if(pjConsultBean.getBusinessAbode()!=null && selectVO.getId().equals(pjConsultBean.getBusinessAbode())) {
				pjConsultBean.setBusinessAbodeName(selectVO.getName());
			}
		}
		
	}
}
